//https://leetcode.cn/problems/sum-of-left-leaves/
package codeRandomThoughts.Test404左叶子之和;

import codeRandomThoughts.utils.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

//二刷 层序遍历
public class Solution4 {
    //当前节点左孩子之和等于其左子树左孩子之和加右子树左孩子之和
    public int sumOfLeftLeaves(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root != null) {
            queue.offer(root);
        }

        int sum = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (node.left != null && (node.left.left == null && node.left.right == null)) {
                    sum += node.left.val;
                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
        }

        return sum;
    }
}
